package com.hyts.fscan.tools;

import java.io.File;
import java.io.FileFilter;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;

public class BFileScanHelper {
	
	/**
	 * 扫描服务操作
	 * @param path 路径
	 * @param recursive 是否递归
 	 * @return
	 */
	public static List<File> scanFiles(String path,FileFilter fileFilter,boolean recursive){
		List<File> fileList = new LinkedList<>();
		Object VoidObj = recursive?scanFilesByRecursive(path,fileFilter,fileList):
			scanFilesByNotRecursive(path,fileFilter,fileList);
		System.out.println(VoidObj);
		return fileList;
	}
	
	/**
	 * 递归方式扫描机制
	 * @param path
	 * @return
	 */
	private static Void scanFilesByRecursive(String path,FileFilter filter,List<File> fileList){
		if(StringUtils.isNoneBlank(path)) {
			File file = new File(path);
			File[] files = filter == null?file.listFiles():file.listFiles(filter);
			for(File fileObj:files) {
				if(fileObj.isDirectory()) {
					scanFilesByRecursive(fileObj.getAbsolutePath(),filter,fileList);
				}else {
					fileList.add(fileObj);
				}
			}
		}
		return null;
	}
	
	/**
	 * 非递归方式扫描机制
	 * @param path
	 * @return
	 */
	private static Void scanFilesByNotRecursive(String path,FileFilter filter,List<File> fileList){
	    if(StringUtils.isNoneBlank(path)) {
			List<File> dataList = Stream.of((new File(path)).
					listFiles(filter)).collect(Collectors.toList());
			for(;!dataList.isEmpty();) {
				File file = dataList.remove(0);
				File[] files = filter == null? file.listFiles():file.listFiles(filter);
				for(File fileElement:files) {
					if(fileElement.isDirectory()) {
						dataList.add(file);
					}else {
						fileList.add(file);
					}
				}
			}
		}
		return null;
	}
}
